package com.base.social.auth.request;

import com.base.core.enums.SystemCodeEnum;
import com.base.core.utils.JacksonUtils;
import com.base.core.utils.R;
import com.base.core.utils.UrlBuilderUtils;
import com.base.core.web.http.HttpClientUtils;
import com.base.social.cache.AuthStateCache;
import com.base.social.config.AuthConfig;
import com.base.social.config.AuthDefaultSource;
import com.base.social.domain.AuthCallbackParams;
import com.base.social.domain.AuthToken;
import com.base.social.domain.AuthUser;
import com.base.social.enums.AuthUserGender;
import com.base.social.exception.AuthRuntimeException;
import com.base.social.auth.AuthDefault;

import java.util.Map;

/**
 * 微信小程序登录
 *
 * @author becker
 * @since 0.0.1
 */
public class AuthWeChatMini extends AuthDefault {
    public AuthWeChatMini(AuthConfig config) {
        super(config, AuthDefaultSource.WECHAT_MINI);
    }

    public AuthWeChatMini(AuthConfig config, AuthStateCache authStateCache) {
        super(config, AuthDefaultSource.WECHAT_MINI, authStateCache);
    }

    /**
     * 微信的特殊性，此时返回的信息同时包含 openid 和 access_token
     *
     * @param authCallback 回调返回的参数
     * @return 所有信息
     */
    @Override
    protected AuthToken createAccessToken(AuthCallbackParams authCallback) {
        return this.getToken(accessTokenUrl(authCallback.getCode()));
    }

    @Override
    public AuthUser findUserInfo(AuthToken authToken) {
        String openId = authToken.getOpenId();

        String response = doGetUserInfo(authToken);
        Map<String,Object> object = JacksonUtils.toMap(response);

        this.checkResponse(object);

        String location = String.format("%s-%s-%s", object.get("country").toString(),
                object.get("province").toString(), object.get("city").toString());

        if (object.containsKey("unionid")) {
            authToken.setUnionId(object.get("unionid").toString());
        }

        return AuthUser.builder()
                .username(object.get("nickname").toString())
                .nickname(object.get("nickname").toString())
                .avatar(object.get("headimgurl").toString())
                .location(location)
                .openid(openId)
                .gender(AuthUserGender.wechatRealGender(object.get("sex").toString()))
                .token(authToken)
                .source(source.toString())
                .build();
    }

    @Override
    public R refresh(AuthToken oldToken) {
        return R.success(this.getToken(refreshTokenUrl(oldToken.getRefreshToken())));
    }

    /**
     * 检查响应内容是否正确
     *
     * @param object 请求响应内容
     */
    private void checkResponse(Map object) {
        if (object.containsKey("errcode")) {
            throw new AuthRuntimeException(Integer.parseInt(object.get("errcode").toString()), object.get("errmsg").toString());
        }
    }

    /**
     * 获取token，适用于获取access_token和刷新token
     *
     * @param accessTokenUrl 实际请求token的地址
     * @return token对象
     */
    private AuthToken getToken(String accessTokenUrl) {
        String response = HttpClientUtils.get(accessTokenUrl);
        Map<String, Object> accessTokenObject = JacksonUtils.toMap(response);

        this.checkResponse(accessTokenObject);

        return AuthToken.builder()
//                .accessToken(accessTokenObject.get("access_token").toString())
//                .refreshToken(accessTokenObject.get("refresh_token").toString())
//                .expireIn(Integer.parseInt(accessTokenObject.get("expires_in").toString()))
                .openId(accessTokenObject.get("openid").toString())
                .build();
    }

    /**
     * 返回带{@code state}参数的授权url，授权回调时会带上这个{@code state}
     *
     * @param state state 验证授权流程的参数，可以防止csrf
     * @return 返回授权地址
     * @since 1.9.3
     */
    @Override
    public String authorize(String state) {
        throw new AuthRuntimeException(SystemCodeEnum.NOT_IMPLEMENTED);
    }

    /**
     * 返回获取accessToken的url
     *
     * @param code 授权码
     * @return 返回获取accessToken的url
     */
    @Override
    protected String accessTokenUrl(String code) {
        return UrlBuilderUtils.fromBaseUrl(source.accessToken())
                .queryParam("js_code", code)
                .queryParam("appid", config.getClientId())
                .queryParam("secret", config.getClientSecret())
                .queryParam("grant_type", "authorization_code")
                .build();
    }

    /**
     * 返回获取userInfo的url
     *
     * @param authToken 用户授权后的token
     * @return 返回获取userInfo的url
     */
    @Override
    protected String userInfoUrl(AuthToken authToken) {
        return UrlBuilderUtils.fromBaseUrl(source.userInfo())
                .queryParam("access_token", authToken.getAccessToken())
                .queryParam("openid", authToken.getOpenId())
                .queryParam("lang", "zh_CN")
                .build();
    }

    /**
     * 返回获取userInfo的url
     *
     * @param refreshToken getAccessToken方法返回的refreshToken
     * @return 返回获取userInfo的url
     */
    @Override
    protected String refreshTokenUrl(String refreshToken) {
        return UrlBuilderUtils.fromBaseUrl(source.refresh())
                .queryParam("appid", config.getClientId())
                .queryParam("refresh_token", refreshToken)
                .queryParam("grant_type", "refresh_token")
                .build();
    }
}
